package com.hoe.tsb.fraft.net;

import com.hoe.tsb.Configuration;

/**
 * <p>
 * 抽象数据交换器
 * </p>
 *
 * @author hoe
 * @since 2022/11/21
 */
public abstract class AbstractExchanger implements Exchanger {

    private MessageReceive msgReceive;
    /**
     * 收到关闭指令，即将关闭
     */
    protected boolean willClose = false;
    /**
     * 交换器接收端的IP和端口
     */
    protected String ip;
    protected int port;

    public AbstractExchanger(Configuration config) {
        this(config.getCurrent().getIp(), config.getCurrent().getPort());
    }

    /**
     * 无参构造函数子类必须实现<br/>
     * 数据交换器工厂需要使用该构造函数进行实例化
     */
    public AbstractExchanger(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void setReceiver(MessageReceive rcv) {
        this.msgReceive = rcv;
    }

    @Override
    public void close() {
        willClose = true;
        onClose();
    }

    protected MessageReceive getReceiver() {
        return msgReceive;
    }

    /**
     * 用于子类做一些特殊的关闭工作
     */
    protected void onClose() {
        //do nothing
    }

}
